import React from 'react';
import {Table, Message as componentMessage, Spin, Affix, Alert, Row, Col, Popconfirm} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {Link} from 'react-router-dom';
import {PAGINATION_OPTIONS, COMMON_TABLE_QUERY_FAIL_TEXT, COMMON_TABLE_EMPTY_TEXT,
    DATETIME_FORMAT, ROWSELECTION_FIXED_COLUMN_WIDTH} from '../constants';
import {PERMISSION} from './constants';
import {injectIntl, language} from './intl';
import {conventEnumValueToString, formatDateTime, formatAmount, exportDownload} from '../utils';
import {hasPermissions} from './utils';
import {claimSettlementStatus, usedPartStatus, repairType, claimStatus} from '../Enum';
import {abandonData, submitData, exportData, downloadInfo} from './api';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import DropdownMenu from 'Shared/components/DropdownMenu';
import Ellipsis from 'ant-design-pro/lib/Ellipsis';
import style from './style.css';
import stringify from 'Shared/utils/stringify';
import moment from 'moment';
const datetime = moment(new Date()).format('YYYYMMDDhhmmss');
export class TablePanel extends React.PureComponent {
    constructor(props) {
        super(props);
        this.onChangeSort = this.onChangeSort.bind(this);
        this.state = {
            loading: false,
            selectedRowKeys: [],
        };
    }
    affixOnChange = () => this.forceUpdate();
    onChangeSort = (pagination, filters, sorter) => {
        this.props.onChangeSort({
            pageIndex: pagination.current - 1,
            pageSize: pagination.pageSize,
            sortedColumnKey: sorter.columnKey,
            sortedOrder: sorter.order,
        });
    };
    onClickSubmitBtn = id => {
        this.setState({loading: true});
        const record = this.props.list.find(d => d.id === id);
        submitData(id, {rowVersion: record.rowVersion})
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.refreshListData();
            });
    }
    onClickAbandonBtn = id => {
        this.setState({loading: true});
        const record = this.props.list.find(d => d.id === id);
        abandonData(id, {rowVersion: record.rowVersion})
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.refreshListData();
            });
    }
    onClickExportBtn = id => {
        this.setState({loading: true});
        exportData(id)
            .then(res => {
                this.setState({loading: false});
                exportDownload(res.data);
            });
    }
    onUsedLabelPrint = e => {
        e.stopPropagation();
        window.open(`afterSales/print/report.html?id=${e.currentTarget.dataset.id}&name=UsedLable&title=${encodeURI('旧件标签')}`);
    }
    onClickBatchPrint = () => {
        const selectIds = this.state.selectedRowKeys;
        if(selectIds.length === 0)
            componentMessage.warning(this.props.intl.formatMessage({
                id: 'tablePanel.btn.ValidationMessage',
                defaultMessage: '请选择需要批量操作的选项'
            }));
        else {
            const condition = stringify({id: selectIds});
            window.open(`afterSales/print/report.html?${condition}&name=UsedLable&title=${encodeURI('旧件标签')}`);
        }
    }
    onClickDownload = () => {
        const selectIds = this.state.selectedRowKeys;
        if(selectIds.length === 0)
            componentMessage.warning(this.props.intl.formatMessage({
                id: 'tablePanel.btn.ValidationMessage',
                defaultMessage: '请选择需要批量操作的选项'
            }));
        else {
            this.setState({loading: true});
            const data = this.props.list.filter(item => selectIds.includes(item.id)).map(item => item.id);
            downloadInfo({
                filePath: `${this.props.user}-${datetime}`,
                claimIds: data
            }).then(res => {
                this.setState({loading: false});
                if(res.ok) {
                    this.props.onChangeSort();
                    this.onEndDownloadOperation();
                    this.props.onConditionsChange('isDownload', false);
                }
            });
        }
    }
    onEndBatchOperation = () => {
        this.setState({selectedRowKeys: []});
        this.props.onEndBatchOperation();
    }
    onEndDownloadOperation = () => {
        this.setState({selectedRowKeys: []});
        this.props.onEndDownloadOperation();
        this.props.onConditionsChange('isDownload', false);
    }
    onSelectedChange = keys => this.setState({
        selectedRowKeys: keys,
    });
    render() {
        const languageIntl = language;
        const isShowBatchPrintPanel = this.props.isShowBatchPrintPanel;
        const isShowDownloadPanel = this.props.isShowDownloadPanel;
        const batchPrintMessage = (<Row>
            <Col span={18}>{
                this.props.intl.formatMessage({
                    id: 'tablePanel.Validation.Message',
                    defaultMessage: '正在进行批量操作，点击右侧关闭将退出操作'
                })
            }</Col>
            <Col span={6} className="col-align-right">
                <Popconfirm
                    id="batchPrint"
                    key="batchPrint"
                    getPopupContainer={this.getPopupContainer} title={this.props.intl.formatMessage({
                        id: 'tablePanel.Validation.isContinue',
                        defaultMessage: '是否继续?'
                    })} okText={this.props.intl.formatMessage({
                        id: 'tablePanel.btn.Confirm',
                        defaultMessage: '确认'
                    })}
                    cancelText={this.props.intl.formatMessage({
                        id: 'tablePanel.btn.Cancel',
                        defaultMessage: '取消'
                    })}
                    onConfirm={this.onClickBatchPrint}>
                    <a className={style.panelalertMessage} >{this.props.intl.formatMessage({
                        id: 'tablePanel.btn.BatchPrint',
                        defaultMessage: '批量打印'
                    })}</a>
                </Popconfirm>
            </Col>
        </Row>);
        const downloadMessage = (<Row>
            <Col span={18}>{
                this.props.intl.formatMessage({
                    id: 'tablePanel.Validation.Message',
                    defaultMessage: '正在进行批量操作，点击右侧关闭将退出操作'
                })
            }</Col>
            <Col span={6} className="col-align-right">
                <Popconfirm
                    id="download"
                    key="download"
                    getPopupContainer={this.getPopupContainer} title={this.props.intl.formatMessage({
                        id: 'tablePanel.Validation.isContinue',
                        defaultMessage: '是否继续?'
                    })} okText={this.props.intl.formatMessage({
                        id: 'tablePanel.btn.Confirm',
                        defaultMessage: '确认'
                    })}
                    cancelText={this.props.intl.formatMessage({
                        id: 'tablePanel.btn.Cancel',
                        defaultMessage: '取消'
                    })}
                    onConfirm={this.onClickDownload}>
                    <a className={style.panelalertMessage} >{this.props.intl.formatMessage({
                        id: 'tablePanel.btn.download',
                        defaultMessage: '批量下载'
                    })}</a>
                </Popconfirm>
            </Col>
        </Row>);
        const colums = [
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.code',
                    defaultMessage: '索赔单号'
                }),
                dataIndex: 'code',
                width: languageIntl === 'pt-PT' ? 260 : 190,
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'code' && this.props.sortedOrder,
                render: (text, record) => <Link to={routes.detail.format(record.id)} >{text}</Link>
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.status',
                    defaultMessage: '状态'
                }),
                dataIndex: 'status',
                width: languageIntl === 'pt-PT' ? 150 : 120,
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'status' && this.props.sortedOrder,
                render: text => conventEnumValueToString(claimStatus, text)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.repairCode',
                    defaultMessage: '维修单号'
                }),
                dataIndex: 'repairCode',
                width: languageIntl === 'pt-PT' ? 260 : 195,
                render: text => <span title={text}><Ellipsis length={20}>{text}</Ellipsis></span>
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.subDealerCode',
                    defaultMessage: '经销商编号'
                }),
                dataIndex: 'subDealerCode',
                width: languageIntl === 'pt-PT' ? 260 : 195,
                render: text => <span title={text}><Ellipsis length={20}>{text}</Ellipsis></span>
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.causePartCode',
                    defaultMessage: '主损件编号'
                }),
                dataIndex: 'causePartCode',
                width: languageIntl === 'pt-PT' ? 260 : 195,
                render: text => <span title={text}><Ellipsis length={20}>{text}</Ellipsis></span>
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.causePartName',
                    defaultMessage: '主损件名称'
                }),
                dataIndex: 'causePartName',
                width: 280,
                render: text => <span title={text}><Ellipsis length={28}>{text}</Ellipsis></span>
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.vin',
                    defaultMessage: 'VIN'
                }),
                dataIndex: 'vin',
                width: 170,
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'vin' && this.props.sortedOrder
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.productCategoryCode',
                    defaultMessage: '车型'
                }),
                dataIndex: 'productCategoryCode',
                width: languageIntl === 'pt-PT' ? 170 : 150,
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'productCategoryCode' && this.props.sortedOrder
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.isKd',
                    defaultMessage: 'CBU/KD'
                }),
                dataIndex: 'isKd',
                width: 100,
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'isKd' && this.props.sortedOrder,
                render: text => {
                    if(text === true)
                        return this.props.intl.formatMessage({
                            id: 'tablePanel.column.kd',
                            defaultMessage: 'KD'
                        });
                    if(text === false)
                        return this.props.intl.formatMessage({
                            id: 'tablePanel.column.cbu',
                            defaultMessage: 'CBU'
                        });
                    return text;
                }
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.settlementStatus',
                    defaultMessage: '结算状态'
                }),
                dataIndex: 'settlementStatus',
                width: languageIntl === 'pt-PT' ? 180 : 150,
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'settlementStatus' && this.props.sortedOrder,
                render: text => conventEnumValueToString(claimSettlementStatus, text)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.usedPartStatus',
                    defaultMessage: '旧件状态'
                }),
                dataIndex: 'usedPartStatus',
                width: languageIntl === 'pt-PT' ? 180 : 150,
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'usedPartStatus' && this.props.sortedOrder,
                render: text => conventEnumValueToString(usedPartStatus, text)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.repairType',
                    defaultMessage: '索赔类型'
                }),
                dataIndex: 'repairType',
                width: languageIntl === 'pt-PT' ? 150 : 120,
                render: text => conventEnumValueToString(repairType, text)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.subClaimCode',
                    defaultMessage: '经销商申请单号'
                }),
                dataIndex: 'subClaimCode',
                width: languageIntl === 'pt-PT' ? 340 : 200,
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'subClaimCode' && this.props.sortedOrder
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.createTime',
                    defaultMessage: '创建时间'
                }),
                dataIndex: 'createTime',
                width: 170,
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'createTime' && this.props.sortedOrder,
                render: text => formatDateTime(text, DATETIME_FORMAT)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.submitTime',
                    defaultMessage: '提交时间'
                }),
                dataIndex: 'submitTime',
                width: 170,
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'submitTime' && this.props.sortedOrder,
                render: text => formatDateTime(text, DATETIME_FORMAT)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.approveTime',
                    defaultMessage: '审核时间'
                }),
                dataIndex: 'approveTime',
                width: 180,
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'approveTime' && this.props.sortedOrder,
                render: text => formatDateTime(text, DATETIME_FORMAT)
            }];
        if(!this.props.isDealerUser) {
            colums.splice(0, 0, ...[
                {
                    title: this.props.intl.formatMessage({
                        id: 'tablePanel.column.dealer',
                        defaultMessage: '总代'
                    }),
                    dataIndex: 'dealerCode',
                    width: 100,
                }
            ]);
            colums.splice(20, 0, ...[
                {
                    title: this.props.intl.formatMessage({
                        id: 'tablePanel.column.adjustedTime',
                        defaultMessage: '调整时间'
                    }),
                    dataIndex: 'adjustedTime',
                    width: 180,
                    sorter: true,
                    sortOrder: this.props.sortedColumnKey === 'adjustedTime' && this.props.sortedOrder,
                    render: text => formatDateTime(text, DATETIME_FORMAT)
                }
            ]);
        }
        if(!this.props.isMoneyVisible)
            colums.splice(12, 0, ...[
                {
                    title: this.props.intl.formatMessage({
                        id: 'tablePanel.column.totalFee',
                        defaultMessage: '费用合计'
                    }),
                    dataIndex: 'totalFee',
                    width: 100,
                    render: text => formatAmount(text)
                }
            ]);
        if(!isShowBatchPrintPanel && !isShowDownloadPanel)
            colums.push({
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.operation',
                    defaultMessage: '操作'
                }),
                dataIndex: 'id',
                key: 'id',
                width: 160,
                fixed: 'right',
                render: (text, r) => {
                    const menus = [{
                        id: PERMISSION.update,
                        children: <Link key="update" to={routes.update.format(r.id)}>{
                            this.props.intl.formatMessage({
                                id: 'tablePanel.update',
                                defaultMessage: '编辑'
                            })
                        }</Link>,
                        hidden: !(hasPermissions(this.props.permissions, PERMISSION.update) && hasPermissions(r.options, PERMISSION.update)),
                    }, {
                        id: PERMISSION.approve,
                        children: <Link key="approve" to={routes.approve.format(r.id)}>{
                            this.props.intl.formatMessage({
                                id: 'tablePanel.approve',
                                defaultMessage: '审核'
                            })
                        }</Link>,
                        hidden: !(hasPermissions(this.props.permissions, PERMISSION.approve) && hasPermissions(r.options, PERMISSION.approve)),
                    }, {
                        id: PERMISSION.adjust,
                        children: <Link key="adjust" to={routes.adjust.format(r.id)}>{
                            this.props.intl.formatMessage({
                                id: 'tablePanel.adjust',
                                defaultMessage: '调整'
                            })
                        }</Link>,
                        hidden: !(hasPermissions(this.props.permissions, PERMISSION.adjust) && hasPermissions(r.options, PERMISSION.adjust)),
                    }, {
                        id: PERMISSION.abandon,
                        children: (ref =>
                            <WrappedPopconfirm
                                key="abandon"
                                placement="topLeft"
                                onConfirm={this.onClickAbandonBtn}
                                id={r.id}
                                onVisibleChange={ref.setMenuVisible}
                                title={this.props.intl.formatMessage({
                                    id: 'tablePanel.validate.abandon',
                                    defaultMessage: '是否确认作废？'
                                })}>
                                <a>{
                                    this.props.intl.formatMessage({
                                        id: 'tablePanel.abandon',
                                        defaultMessage: '作废'
                                    })
                                }</a>
                            </WrappedPopconfirm>
                        ),
                        hidden: !(hasPermissions(this.props.permissions, PERMISSION.abandon) && hasPermissions(r.options, PERMISSION.abandon)),
                    }, {
                        id: PERMISSION.export,
                        children: (ref =>
                            <WrappedPopconfirm
                                key="export"
                                placement="topLeft"
                                onConfirm={this.onClickExportBtn}
                                id={r.id}
                                onVisibleChange={ref.setMenuVisible}
                                title={this.props.intl.formatMessage({
                                    id: 'tablePanel.validate.export',
                                    defaultMessage: '是否确认导出？'
                                })}>
                                <a>{
                                    this.props.intl.formatMessage({
                                        id: 'tablePanel.export',
                                        defaultMessage: '导出'
                                    })
                                }</a>
                            </WrappedPopconfirm>
                        ),
                        hidden: !(hasPermissions(this.props.permissions, PERMISSION.export) && hasPermissions(r.options, PERMISSION.export)),
                    }, {
                        id: PERMISSION.usedLabelPrint,
                        children: (
                            <a key="usedLabelPrint" data-id={r.id} onClick={this.onUsedLabelPrint}>
                                { this.props.intl.formatMessage({
                                    id: 'tablePanel.usedLabelPrint',
                                    defaultMessage: '旧件标签打印'
                                })
                                }
                            </a>
                        ),
                        hidden: !(hasPermissions(this.props.permissions, PERMISSION.usedLabelPrint) && hasPermissions(r.options, PERMISSION.usedLabelPrint)),
                    }];
                    return <DropdownMenu key={r.id} menus={menus} primaryLength={1} id={r.id} />;
                }
            });
        
        const pagination = {
            total: this.props.total,
            pageSize: this.props.pageSize,
            current: this.props.pageIndex + 1,
            ...PAGINATION_OPTIONS
        };
        const locale = {
            emptyText: this.props.errorMessage ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
        };
        const rowSelection = isShowBatchPrintPanel || isShowDownloadPanel ? {
            fixed: true,
            type: 'checkbox',
            columnWidth: ROWSELECTION_FIXED_COLUMN_WIDTH,
            getCheckboxProps: record => ({
                disabled: !hasPermissions(record.options, PERMISSION.usedLabelPrint)
            }),
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: this.onSelectedChange
        } : undefined;
        return (
            <Spin spinning={this.props.loading || this.state.loading} className={style.spin}>
                {isShowBatchPrintPanel && <Affix offsetTop={0} className={style.alertMargin}
                    onChange={this.affixOnChange}>
                    <Alert message={batchPrintMessage} type="warning" closable showIcon
                        closeText={<span className={style.closeText}>{this.props.intl.formatMessage({
                            id: 'tablePanel.btn.close',
                            defaultMessage: '关闭'
                        })}</span>} onClose={this.onEndBatchOperation} />
                </Affix>}
                {isShowDownloadPanel && <Affix offsetTop={0} className={style.alertMargin}
                    onChange={this.affixOnChange}>
                    <Alert message={downloadMessage} type="warning" closable showIcon
                        closeText={<span className={style.closeText}>{this.props.intl.formatMessage({
                            id: 'tablePanel.btn.close',
                            defaultMessage: '关闭'
                        })}</span>} onClose={this.onEndDownloadOperation} />
                </Affix>}
                <Table
                    className="white-space-nowrap"
                    columns={colums}
                    dataSource={this.props.list}
                    onChange={this.onChangeSort}
                    rowKey="id"
                    pagination={pagination}
                    locale={locale}
                    rowSelection={rowSelection}
                    scroll={{
                        x: 'max-content',
                        y: 540}}
                    size="small"
                    bordered={true} />
            </Spin>
        );
    }
}

TablePanel.propTypes = {
    errorMessage: PropTypes.string.isRequired,
    isShowBatchPrintPanel: PropTypes.bool.isRequired,
    isShowDownloadPanel: PropTypes.bool.isRequired,
    list: PropTypes.array.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    total: PropTypes.number.isRequired,
    onChangeSort: PropTypes.func.isRequired,
    onConditionsChange: PropTypes.func.isRequired,
    onEndBatchOperation: PropTypes.func.isRequired,
    onEndDownloadOperation: PropTypes.func.isRequired,
    intl: PropTypes.object,
    isDealerUser: PropTypes.bool,
    isMoneyVisible: PropTypes.bool,
    pageIndex: PropTypes.number,
    pageSize: PropTypes.number,
    refreshListData: PropTypes.func,
    sortedColumnKey: PropTypes.string,
    sortedOrder: PropTypes.string,
    user: PropTypes.string,
};

import {connect} from 'react-redux';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {tableSearch, clearBatchData, clearDownload, saveQueryCondition} from './actions';

const getData = selectorFactory(['page', 'domainData', 'list', 'data']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    isDealerUser: state.getIn((['page', 'domainData', 'initData', 'isDealerUser'])),
    list: getData(state),
    total: state.getIn(['page', 'domainData', 'list', 'total']),
    pageIndex: state.getIn(['page', 'appState', 'queryBySort', 'pageIndex']),
    pageSize: state.getIn(['page', 'appState', 'queryBySort', 'pageSize']),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    errorMessage: state.getIn(['page', 'domainData', 'list', 'message']),
    sortedColumnKey: state.getIn(['page', 'appState', 'queryBySort', 'sortedColumnKey']),
    sortedOrder: state.getIn(['page', 'appState', 'queryBySort', 'sortedOrder']),
    isShowBatchPrintPanel: state.getIn(['page', 'ui', 'showBatchPrintPanel']),
    isShowDownloadPanel: state.getIn(['page', 'ui', 'showDownloadPanel']),
    user: state.getIn(['page', 'domainData', 'initData', 'user']),
    isMoneyVisible: state.getIn((['page', 'domainData', 'initData', 'isMoneyVisible'])),
    permissions: getPermissions(state),
});

const mapDispatchToProps = dispatch => ({
    onChangeSort: option => dispatch(tableSearch(option)),
    refreshListData: () => dispatch(tableSearch()),
    onEndBatchOperation: () => dispatch(clearBatchData()),
    onEndDownloadOperation: () => dispatch(clearDownload()),
    onConditionsChange: (name, value) => dispatch(saveQueryCondition(name, value)),
});

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(TablePanel));
